#include "StdAfx.h"
#include "ProtocolFactory.h"

namespace RoomFW {

void ProtocolFactory::Register(IContractCheckerSPC contract)
{
	CriticalSectionGuard g = ProtocolFactory::Guard();

	ProtocolFactory::GetProtocolMap()[contract->getTypeID()] =
		std::make_pair(contract, contract->getConjugate());
}

IContractCheckerSPC ProtocolFactory::Get(ContractTypeId typeId, bool conjugate)
{
	IContractCheckerSPC retVal;

	CriticalSectionGuard g = ProtocolFactory::Guard();
	
	ProtocolMap& theMap = ProtocolFactory::GetProtocolMap();
	ProtocolMap::const_iterator i = theMap.find(typeId);
	if (theMap.end() != i)
	{
		const ProtocolPair& pp = i->second;
		retVal = (conjugate ? pp.second : pp.first);
	}
	return retVal;
}

ProtocolFactory::ProtocolMap& ProtocolFactory::GetProtocolMap()
{
	static ProtocolMap theMap;
	return theMap;
}

CriticalSectionGuard ProtocolFactory::Guard()
{
	static SimpleCriticalSection cs_;
	return CriticalSectionGuard(cs_);
}

ProtocolFactoryRegistration::ProtocolFactoryRegistration(IContractCheckerSPC contract)
{
	ProtocolFactory::Register(contract);
}

}
